import React, { useState, useEffect } from 'react';
import {Badge, List, Avatar, Button, Tag, Empty, Spin, Tabs, Layout, Typography, Pagination} from 'antd';
import {BellOutlined, MessageOutlined, NotificationOutlined, CloseOutlined, CheckCircleOutlined} from '@ant-design/icons';

const { Content } = Layout;
const { TabPane } = Tabs;
const { Title } = Typography;

const primaryColor = '#1890ff';
const textColor = 'rgba(0, 0, 0, 0.85)';
const textColorSecondary = 'rgba(0, 0, 0, 0.45)';
const itemHoverBg = '#f5f5f5';

// 模拟数据
const mockMessages = [
    { id: '1', type: 'notification', title: '系统升级通知', content: '系统将于今晚24:00进行升级维护，预计耗时2小时。升级期间系统将无法访问，请提前安排好工作。', time: '2023-05-15 14:30', read: false, avatar: null },
    { id: '2', type: 'message', title: '新消息', content: '您提交的订单已经处理完成，请及时查看订单详情。如有任何问题，请联系客服支持。', time: '2023-05-15 10:15', read: false, avatar: 'https://randomuser.me/api/portraits/men/1.jpg' },
    { id: '3', type: 'alert', title: '安全提醒', content: '检测到您的账号在异地登录，登录地点：上海市。如非本人操作请立即修改密码。', time: '2023-05-14 18:45', read: true, avatar: null },
    { id: '4', type: 'message', title: '退款通知', content: '您的退款申请已通过审核，款项将在3个工作日内退回至原支付账户。', time: '2023-05-14 09:20', read: true, avatar: 'https://randomuser.me/api/portraits/women/2.jpg' },
    { id: '5', type: 'notification', title: '新功能上线', content: '数据分析模块已全面升级，新增多维度统计功能，欢迎体验并提供宝贵意见。', time: '2023-05-13 16:10', read: true, avatar: null },
    { id: '6', type: 'alert', title: '账号安全', content: '您的账号密码强度较弱，建议尽快修改密码以保障账号安全。', time: '2023-05-12 11:30', read: false, avatar: null },
    { id: '7', type: 'message', title: '会议提醒', content: '您有一个团队会议安排在今天下午15:00，主题：项目进度汇报，请准时参加。', time: '2023-05-11 09:00', read: true, avatar: 'https://randomuser.me/api/portraits/men/3.jpg' },
    { id: '8', type: 'notification', title: '系统更新', content: '新版本V2.3.0已发布，修复了已知问题，优化了系统性能。', time: '2023-05-10 17:20', read: true, avatar: null }
];

const NotificationCenter = () => {
    const [loading, setLoading] = useState(false);
    const [messages, setMessages] = useState([]);
    const [unreadCount, setUnreadCount] = useState(0);
    const [activeTab, setActiveTab] = useState('all');

    const [currentPage, setCurrentPage] = useState(1);
    const pageSize = 10; // 固定每页 10 条

    useEffect(() => {
        setLoading(true);
        setTimeout(() => {
            setMessages(mockMessages);
            setUnreadCount(mockMessages.filter(msg => !msg.read).length);
            setLoading(false);
        }, 800);
    }, []);

    const markAllAsRead = () => {
        setMessages(prev => prev.map(msg => ({ ...msg, read: true })));
        setUnreadCount(0);
    };

    const clearRead = () => {
        setMessages(prev => prev.filter(msg => !msg.read));
        setUnreadCount(prev => prev); // 未读数量不变
    };

    const markAsRead = (id) => {
        setMessages(prev => prev.map(msg =>
            msg.id === id ? { ...msg, read: true } : msg
        ));
        setUnreadCount(prev => Math.max(prev - 1, 0));
    };

    const deleteMessage = (id) => {
        const message = messages.find(msg => msg.id === id);
        if (message && !message.read) {
            setUnreadCount(prev => Math.max(prev - 1, 0));
        }
        setMessages(prev => prev.filter(msg => msg.id !== id));
    };

    const getMessageIcon = (type) => {
        switch (type) {
            case 'notification': return <NotificationOutlined style={{ color: '#1890ff' }} />;
            case 'message': return <MessageOutlined style={{ color: '#52c41a' }} />;
            case 'alert': return <NotificationOutlined style={{ color: '#f5222d' }} />;
            default: return <BellOutlined />;
        }
    };

    // 按 tab 过滤数据
    const filteredMessages = activeTab === 'all'
        ? messages
        : messages.filter(msg => msg.type === activeTab);

    const pagedMessages = filteredMessages.slice(
        (currentPage - 1) * pageSize,
        currentPage * pageSize
    );

    const notificationMessages = messages.filter(m => m.type === 'notification').length;
    const alertMessages = messages.filter(m => m.type === 'alert').length;
    const messageMessages = messages.filter(m => m.type === 'message').length;

    return (
        <Content
            style={{
                background: '#fff',
                padding: '24px',
                borderRadius: 8,
                height: 'calc(100vh - 70px - 12px)',
                display: 'flex',
                flexDirection: 'column'
            }}
        >
            {/* 顶部操作栏 */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
                <Title level={4} style={{ margin: 0 }}>消息通知</Title>
                <div>
                    <Button
                        type="primary"
                        onClick={markAllAsRead}
                        disabled={unreadCount === 0}
                        style={{ marginRight: 8 }}
                    >
                        全部已读
                    </Button>
                    <Button onClick={clearRead}>清除已读</Button>
                </div>
            </div>

            {/* Tabs */}
            <Tabs
                activeKey={activeTab}
                onChange={(key) => {
                    setActiveTab(key);
                    setCurrentPage(1);
                }}
            >
                <TabPane tab={`全部 (${messages.length})`} key="all" />
                <TabPane
                    tab={
                        <Badge count={messages.filter(m => m.type === 'notification' && !m.read).length} size="small" offset={[10, 0]}>
                            <span>通知 ({notificationMessages})</span>
                        </Badge>
                    }
                    key="notification"
                />
                <TabPane
                    tab={
                        <Badge count={messages.filter(m => m.type === 'message' && !m.read).length} size="small" offset={[10, 0]}>
                            <span>消息 ({messageMessages})</span>
                        </Badge>
                    }
                    key="message"
                />
                <TabPane
                    tab={
                        <Badge count={messages.filter(m => m.type === 'alert' && !m.read).length} size="small" offset={[10, 0]}>
                            <span>提醒 ({alertMessages})</span>
                        </Badge>
                    }
                    key="alert"
                />
            </Tabs>

            {/* 列表区域 */}
            <div style={{ flex: 1, overflowY: 'auto' }}>
                {loading ? (
                    <div style={{ display: 'flex', justifyContent: 'center', padding: '40px 0' }}>
                        <Spin size="large" />
                    </div>
                ) : pagedMessages.length === 0 ? (
                    <Empty
                        image={Empty.PRESENTED_IMAGE_SIMPLE}
                        description="没有找到相关消息"
                        style={{ padding: '40px 0' }}
                    />
                ) : (
                    <List
                        itemLayout="horizontal"
                        dataSource={pagedMessages}
                        renderItem={(item) => (
                            <List.Item
                                style={{
                                    padding: '12px 16px',
                                    backgroundColor: item.read ? 'transparent' : 'rgba(24,144,255,0.05)',
                                    borderBottom: '1px solid #f0f0f0',
                                    transition: 'all 0.3s'
                                }}
                                onMouseEnter={(e) => {
                                    e.currentTarget.style.backgroundColor = item.read ? itemHoverBg : 'rgba(24,144,255,0.08)';
                                }}
                                onMouseLeave={(e) => {
                                    e.currentTarget.style.backgroundColor = item.read ? 'transparent' : 'rgba(24,144,255,0.05)';
                                }}
                                actions={[
                                    <Button
                                        type="text"
                                        icon={<CloseOutlined />}
                                        size="small"
                                        onClick={(e) => {
                                            e.stopPropagation();
                                            deleteMessage(item.id);
                                        }}
                                    />,
                                    !item.read && (
                                        <Button
                                            type="text"
                                            icon={<CheckCircleOutlined />}
                                            size="small"
                                            onClick={(e) => {
                                                e.stopPropagation();
                                                markAsRead(item.id);
                                            }}
                                        />
                                    )
                                ].filter(Boolean)}
                            >
                                <List.Item.Meta
                                    avatar={
                                        item.avatar ? <Avatar src={item.avatar} /> : <Avatar icon={getMessageIcon(item.type)} />
                                    }
                                    title={
                                        <div style={{ display: 'flex', alignItems: 'center' }}>
                                            <span>{item.title}</span>
                                            <Tag
                                                color={item.type === 'alert' ? 'red' : 'blue'}
                                                style={{ marginLeft: 8 }}
                                            >
                                                {item.type === 'notification' ? '通知' :
                                                    item.type === 'message' ? '消息' : '提醒'}
                                            </Tag>
                                            {!item.read && (
                                                <span style={{
                                                    display: 'inline-block',
                                                    width: 6,
                                                    height: 6,
                                                    borderRadius: '50%',
                                                    backgroundColor: primaryColor,
                                                    marginLeft: 8
                                                }} />
                                            )}
                                        </div>
                                    }
                                    description={
                                        <>
                                            <div style={{ color: textColor, marginBottom: 4 }}>{item.content}</div>
                                            <div style={{ color: textColorSecondary, fontSize: 12 }}>{item.time}</div>
                                        </>
                                    }
                                />
                            </List.Item>
                        )}
                    />
                )}
            </div>

            {/* 分页器固定底部 */}
            <div
                style={{
                    borderTop: '1px solid #f0f0f0',
                    paddingTop: 12,
                    background: '#fff',
                    position: 'sticky',
                    bottom: 0,
                    display: 'flex',
                    justifyContent: 'flex-end'
                }}
            >
                <Pagination
                    current={currentPage}
                    pageSize={pageSize}
                    total={filteredMessages.length}
                    onChange={(page) => setCurrentPage(page)}
                    showSizeChanger={false}
                />
            </div>
        </Content>
    );
};

export default NotificationCenter;
